<template>
    <div
        class="design-slice-list-container relative h-full flex flex-col border-t border-gray-100 border-solid"
        ref="designSliceListRef"
    >
        <!-- 空状态 -->
        <div v-if="!designData?.length" class="text-center text-slate-600 my-8">去 设计稿 页面导入设计稿</div>
        <!-- 有数据 -->
        <el-tabs v-else class="flex-1 overflow-hidden" v-model="currentTab" type="card">
            <el-tab-pane class="h-full" :label="item.name" :name="item.id" v-for="item in designData">
                <el-scrollbar class="design-slice-list bg-slate-200">
                    <!-- 设计稿 -->

                    <div
                        ref="designPreviewDomRef"
                        class="design-preview relative transform origin-top-left select-none"
                        @click="handleDesignClick"
                        @mousedown="handleMousedown"
                        :style="{
                            zoom: scaleFactor
                        }"
                    >
                        <img :src="item.version.url" class="max-w-[unset]" />
                        <div
                            v-for="info in item.infos"
                            class="slice-item absolute left-0 top-0 border-5 border-gray-400 border-dotted bg-opacity-5 cursor-pointer"
                            :class="{
                                'border-red-500': info.id === selectedSlice?.id
                            }"
                            :style="{
                                // left: info.layerOriginFrame?.x + 'px',
                                // top: info.layerOriginFrame?.y + 'px',
                                left: info.left + 'px',
                                top: info.top + 'px',
                                width: info.image?.size.width + 'px',
                                height: info.image?.size.height + 'px'
                                // width: info.layerOriginFrame?.width + 'px',
                                // height: info.layerOriginFrame?.height + 'px'
                            }"
                            @click="(e) => handleSliceClick(e, info)"
                            :data-infoname="info.name"
                            :data-url="info.image?.imageUrl"
                            :data-infoid="info.id"
                        ></div>
                    </div>
                    <div class="h-[120px]"></div>

                    <!-- 预览窗口 -->
                    <!-- <div class="container w-[375px]" :style="{
                        background: `url(${item.version.url}) left top / 100% 100%`,
                        width: `${item.version.width}px`,
                        height: `${item.version.height}px`
                        }"></div> -->

                    <!-- <div class="name mb-2 px-2">{{ item.name }} ({{ item.infos.length }})</div>
                        <div class="items">
                            <div class="item flex mb-2" v-for="info in item.infos">
                                <div class="img transparent-background p-2">
                                    <img class="w-[50px] h-[50px] object-contain" :src="info.image?.imageUrl" alt="" />
                                </div>
                                <div class="info">
                                    <div class="name text-black-600 ml-2">{{ info.name }}</div>
                                </div>
                            </div>
                        </div> -->
                </el-scrollbar>
            </el-tab-pane>
        </el-tabs>

        <!-- 切图预览 -->
        <div
            class="preview absolute bottom-0 left-0 right-0 mx-auto max-w-[300px] m-2 flex items-center p-2 bg-white rounded"
            v-show="selectedSlice"
        >
            <!-- 图片 -->
            <div class="img transparent-background p-2 w-[80px] h-[80px] rounded">
                <img ref="selectedSliceImgRef" class="w-full h-full object-contain" :src="selectedSlice?.image?.imageUrl" alt="" />
            </div>
            <!-- 信息 -->
            <div class="info p-2">
                <div class="name">{{ selectedSlice?.name }}</div>
                <div class="size">设计稿尺寸：{{ selectedSlice?.image?.size.width }} x {{ selectedSlice?.image?.size.height }}</div>
                <div class="size">原始尺寸：{{ naturalSize?.width }} x {{ naturalSize?.height }}</div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { Info } from '@/appUtils/appData/lanhuTypes'
import { DragDataType } from '@/components/DragAndDrop/DragDataTypes'
import { useDrag } from '@/components/DragAndDrop/useDrag'
import { useDesignStore } from '@/stores/design'
import { mouse } from '@/utils/keyboardAndMouse'
import { rectangleContains } from '@/utils/rect'
import { storeToRefs } from 'pinia'
import { onMounted, ref, useTemplateRef } from 'vue'

// store
const designStore = useDesignStore()
const { designData } = storeToRefs(designStore)

console.log(designData.value)

// 当前选中的tab
const currentTab = ref(designData.value[0]?.id || '')
// ref
const designSliceListRef = useTemplateRef('designSliceListRef')
const designPreviewDomRef = useTemplateRef<HTMLDivElement | null>('designPreviewDomRef')
const selectedSliceImgRef = useTemplateRef<HTMLImageElement | null>('selectedSliceImgRef')
// 缩放比例
const scaleFactor = ref(1)
// 被选中的切图
const selectedSlice = ref<Info | null>(null)
const naturalSize = ref<{ width: number; height: number } | null>(null)

// 检测尺寸变化
const observer = new ResizeObserver((entries) => {
    entries.forEach((e) => {
        const { width } = e.contentRect
        scaleFactor.value = width / 750
    })
})

// 图片加载完成事件
const handleSelectedSliceImgLoad = () => {
    if (!selectedSliceImgRef.value) return
    console.dir(selectedSliceImgRef.value)
    const { naturalWidth, naturalHeight } = selectedSliceImgRef.value
    const finalNaturalWidth = Math.round(naturalWidth / 2)
    const finalNaturalHeight = Math.round(naturalHeight / 2)
    naturalSize.value = { width: finalNaturalWidth, height: finalNaturalHeight }
    if (!selectedSlice.value) return
    selectedSlice.value.naturalWidth = finalNaturalWidth
    selectedSlice.value.naturalHeight = finalNaturalHeight
}

// 加载完成后
onMounted(() => {
    const dom = designSliceListRef.value
    if (!dom) return
    observer.observe(dom)
    selectedSliceImgRef.value?.addEventListener('load', handleSelectedSliceImgLoad)
})

// 设计图中的点击
const handleDesignClick = (_e: MouseEvent) => {
    // console.log('design click', e)
}

let lastClickPoint: {
    index: number
    filtered: Info[]
    x: number
    y: number
} = {
    index: 0,
    filtered: [],
    x: 0,
    y: 0
}

const filterInInfo = (info: Info) => {
    const currentData = designData.value.find((v) => v.id === currentTab.value)
    if (!currentData) {
        return [info]
    }
    const infos = currentData.infos
    const filtered = infos.filter((v) => {
        return rectangleContains(info.layerOriginFrame!, v.layerOriginFrame!)
    })
    console.log(filtered)
    return filtered
}

// 切图点击
const handleSliceClick = (e: MouseEvent, item: Info) => {
    let newItem = item
    if (e.x === lastClickPoint.x && e.y === lastClickPoint.y) {
        // 筛选出 item 内的元素
        // const { x, y, width, height } = item.layerOriginFrame
        // const filtered = designData.value
        if (!lastClickPoint.filtered.length) {
            lastClickPoint.filtered = filterInInfo(item)
        }
        if (lastClickPoint.filtered.length > 1) {
            // 索引循环
            const index = (lastClickPoint.index + 1) % lastClickPoint.filtered.length
            newItem = lastClickPoint.filtered[index]
            lastClickPoint.index = index
        }
    } else {
        lastClickPoint = {
            x: e.x,
            y: e.y,
            filtered: [],
            index: 0
        }
    }
    console.log(newItem)
    selectedSlice.value = newItem
}

const handleMousedown = (e: MouseEvent) => {
    let fileItemTarget = e.target as HTMLElement

    if (fileItemTarget.tagName === 'INPUT') return
    // 查找文件项
    while (
        fileItemTarget &&
        !fileItemTarget.classList.contains('slice-item') &&
        fileItemTarget !== designPreviewDomRef.value
    ) {
        fileItemTarget = fileItemTarget.parentElement!
    }
    if (!fileItemTarget) return
    const infoid = fileItemTarget.dataset.infoid
    // 如果当前项是被选中的，则开始拖拽
    if (!infoid || selectedSlice.value?.id !== infoid) {
        return
    }
    const info = selectedSlice.value

    // console.log('info', info)

    const { dragStart } = useDrag<Info>(
        {
            type: DragDataType.SliceItemInfo,
            data: info
        },
        {
            onDragStart: () => {
                mouse.setText(info.name)
                // keyboard.on('pressingChange', updateMouseTxt)
            },
            onDragEnd: () => {
                mouse.setText()
                // keyboard.off('pressingChange', updateMouseTxt)
            }
        }
    )
    dragStart()
}
</script>

<style scoped>
::v-deep .el-tabs__header {
    margin-bottom: 0;
}

::v-deep .el-tabs__item {
    height: 30px;
}
</style>
